#import "CTPersonalVC.h"
#import "CTInfoCell.h"
#import "CTRowData.h"
#import "CTSectionData.h"
#import "TJPickerView.h"
#import "CTHeaderTitleView.h"
#import "CTPickerDataModel.h"
#import <YBPopupMenu.h>
@interface CTPersonalVC () <UITableViewDelegate,UITableViewDataSource,UITabBarControllerDelegate,UIImagePickerControllerDelegate,YBPopupMenuDelegate>
@property (nonatomic ,strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic ,strong) UIButton *nextButton;
@property (nonatomic ,strong) NSArray *educationPickerData;
@property (nonatomic ,strong) NSArray *jobPickerData;
@property (nonatomic ,strong) NSArray *professionPickerData;
@property (nonatomic ,strong) NSArray *salaryPickerData;
@property (nonatomic ,strong) NSArray *maritalPickerData;
@property (nonatomic ,strong) NSArray *residencePickerData;
@property (nonatomic ,strong) NSArray *homeStatePickerData;
@property (nonatomic ,strong) NSArray *cityPickerData;
@property (nonatomic ,strong) NSArray *payDayPickerData;
@property (nonatomic ,strong) NSArray *emailPickerData;
@property (nonatomic ,strong) NSArray *emailTypes;
@property (nonatomic ,assign) BOOL hasPopupMenu;
@property (nonatomic ,strong) CTInfoCell *currentEmailCell;
@end
@implementation CTPersonalVC
- (void)zj_viewWillDisappearForIndex:(NSInteger)index {
    [self.view endEditing:YES];
}
- (void)zj_viewWillAppearForIndex:(NSInteger)index {
    self.pageIndex = index;
    NSDictionary *data = @{
        @"navigationRoute" : NSStringFromClass(self.class),
        @"pageIdentity" : kct_page_personinfo,
        @"elementUniqueIdentifier"  : kct_page_personinfo,
        @"referenceIdentification" : @"",
    };
    [CTUploadManager ct_uploadType:CTUploadTypePage data:data];
    NSDictionary *credtiData = @{
        @"tokenUniqueIdentifier"  : returnBeNil(self.pageModel.operationalTaskID),
        @"errorFlag" : kcredit_point_personinfo,
    };
    [CTUploadManager ct_uploadType:CTUploadTypeCredit data:credtiData];
}
- (void)zj_viewDidLoadForIndex:(NSInteger)index {
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self listConfig];
    [self setUI];
    [self loadPickerData];
    self.emailTypes = @[@"gmail.com", @"yahoo.com", @"yahoo.co.uk", @"hotmail.com", @"outlook.com"];
}
- (void)loadPickerData {
    [self.view showLoading];
    dispatch_group_t group = dispatch_group_create();
    for (int i = 0; i < self.dataArray.count; i++) {
        CTSectionData *sectionModel = self.dataArray[i];
        CTCellElementModel *model = self.pageModel.dataFieldReference[i];
        NSDictionary *paramDic = @{
            @"operationalTaskID" : returnBeNil(self.pageModel.operationalTaskID),
            @"dataFieldDescription" : [NSNumber numberWithInteger:model.dataFieldDescription],
        };
        dispatch_group_enter(group);
        [CTBaseRequest getRequestWithMethodName:CTPath(@"/grantingDatas", CTPathTypeCredit, paramDic) parametersDic:paramDic success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
            dispatch_group_leave(group);
            if (!isSuccess) {
                [self.view showInfoText:(NSString *)responseObject];
            } else {
                NSArray *pickerDatas = [CTPickerDataModel modelArrayWithDictArray:responseObject[@"data"]];
                switch (sectionModel.editType) {
                    case CTCellTypeEducation: {
                        self.educationPickerData = pickerDatas;
                        }
                        break;
                    case CTCellTypeJobStatus: {
                        self.jobPickerData = pickerDatas;
                        }
                        break;
                    case CTCellTypeProfession: {
                        self.professionPickerData = pickerDatas;
                        }
                        break;
                    case CTCellTypeSalary: {
                        self.salaryPickerData = pickerDatas;
                        }
                        break;
                    case CTCellTypeMaritalStatus: {
                        self.maritalPickerData = pickerDatas;
                        }
                        break;
                    case CTCellTypeResidence: {
                        self.residencePickerData = pickerDatas;
                        }
                        break;
                    case CTCellTypeHomeStatus: {
                        self.homeStatePickerData = pickerDatas;
                        }
                        break;
                    case CTCellTypeCity: {
                        self.cityPickerData = pickerDatas;
                        }
                        break;
                    case CTCellTypePayDay: {
                        self.payDayPickerData = pickerDatas;
                        }
                        break;
                    case CTCellTypeSelectEmail: {
                        self.emailPickerData = pickerDatas;
                        }
                        break;
                    default:
                        break;
                }
            }
        }];
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self.view dismissLoading];
    });
}
- (void)loadCityPickerDatas:(NSInteger)index {
    CTCellElementModel *cellModel = self.pageModel.dataFieldReference[index];
    NSNumber *fieldId = [NSNumber numberWithInteger:cellModel.dataFieldDescription];
    NSNumber *parentId = [NSNumber numberWithInteger:self.model.residentialStateInfo.attributeCurrentValue];
    NSDictionary *paramDic = @{
        @"operationalTaskID" : returnBeNil(self.pageModel.operationalTaskID),
        @"dataFieldDescription" : fieldId,
        @"hierarchicalParentKey" : parentId,
    };
    [self.view showLoading];
    [CTBaseRequest getRequestWithMethodName:CTPath(@"/grantingDatas", CTPathTypeCredit, paramDic) parametersDic:paramDic success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        [self.view dismissLoading];
        if (!isSuccess) {
            [self.view showInfoText:(NSString *)responseObject];
        } else {
            NSMutableArray *arrM = [NSMutableArray array];
            NSArray *pickerDatas = [CTPickerDataModel modelArrayWithDictArray:responseObject[@"data"]];
            [pickerDatas enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                CTPickerDataModel *model = obj;
                [arrM addObject:model.attributeCurrentValue];
            }];
            __weak typeof(self) weakSelf = self;
            [TJPickerView showStringPickerWithTitle:cellModel.dataSortingKey dataSources:arrM selectValue:arrM.firstObject completion:^(NSString * _Nonnull select) {
                NSInteger index = [arrM indexOfObject:select];
                CTPickerDataModel *pickerModel = [pickerDatas objectAtIndex:index];
                weakSelf.model.residentialDistrictInfo = [weakSelf toMapCellModel:weakSelf.model.residentialDistrictInfo withPickerModel:pickerModel];
                [weakSelf.tableView reloadData];
            }];
        }
    }];
}
- (void)setUI {
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.nextButton];
}
- (void)listConfig{
    CTRowData * education = [CTRowData new];
    education.placeHolder = @"Please select your highest degree";
    CTSectionData *educationSection = [[CTSectionData alloc] init];
    educationSection.sectionTitle = @"Education";
    educationSection.editType = CTCellTypeEducation;
    [educationSection.sectionData addObject:education];
    CTRowData * jobStatus = [CTRowData new];
    jobStatus.placeHolder = @"Please select your job status";
    CTSectionData *jobSection = [[CTSectionData alloc] init];
    jobSection.editType = CTCellTypeJobStatus;
    jobSection.sectionTitle = @"Job status";
    [jobSection.sectionData addObject:jobStatus];
    CTRowData * profession = [CTRowData new];
    profession.placeHolder = @"Please select your profession";
    CTSectionData *professionSection = [[CTSectionData alloc] init];
    professionSection.editType = CTCellTypeProfession;
    professionSection.sectionTitle = @"Profession";
    [professionSection.sectionData addObject:profession];
    CTRowData * salary = [CTRowData new];
    salary.placeHolder = @"Please select your salary";
    CTSectionData *salarySection = [[CTSectionData alloc] init];
    salarySection.editType = CTCellTypeSalary;
    salarySection.sectionTitle = @"Salary";
    [salarySection.sectionData addObject:salary];
    CTRowData * maritalStatus = [CTRowData new];
    maritalStatus.placeHolder = @"please select your marital status";
    CTSectionData *MaritalSection5 = [[CTSectionData alloc] init];
    MaritalSection5.editType = CTCellTypeMaritalStatus;
    MaritalSection5.sectionTitle = @"Marital status";
    [MaritalSection5.sectionData addObject:maritalStatus];
    CTRowData * residence = [CTRowData new];
    residence.placeHolder = @"please select your Type of residence";
    CTSectionData *residenceSection = [[CTSectionData alloc] init];
    residenceSection.editType = CTCellTypeResidence;
    residenceSection.sectionTitle = @"Type of residence";
    [residenceSection.sectionData addObject:residence];
    CTRowData * state = [CTRowData new];
    state.placeHolder = @"please select state";
    CTSectionData *homeSection = [[CTSectionData alloc] init];
    homeSection.editType = CTCellTypeHomeStatus;
    homeSection.sectionTitle = @"State of home";
    [homeSection.sectionData addObject:state];
    CTRowData * city = [CTRowData new];
    city.placeHolder = @"please select city or area";
    CTSectionData *citySection = [[CTSectionData alloc] init];
    citySection.editType = CTCellTypeCity;
    citySection.sectionTitle = @"";
    [citySection.sectionData addObject:city];
    CTRowData * address = [CTRowData new];
    address.tfModel = [[CTTFModel alloc] init];
    address.placeHolder = @"please fill in the detailed block address";
    CTSectionData *addressSection = [[CTSectionData alloc] init];
    addressSection.editType = CTCellTypeSelectAddress;
    addressSection.sectionTitle = @"Address";
    [addressSection.sectionData addObject:address];
    CTRowData * alternate = [CTRowData new];
    alternate.tfModel = [[CTTFModel alloc] init];
    alternate.placeHolder = @"please use your phone number related to BVN";
    CTSectionData *AlternateSection = [[CTSectionData alloc] init];
    AlternateSection.editType = CTCellTypeSelectAlternateNumber;
    AlternateSection.sectionTitle = @"Alternate number(Optional)";
    [AlternateSection.sectionData addObject:alternate];
    CTRowData * payDay = [CTRowData new];
    payDay.placeHolder = @"please select pay day";
    CTSectionData *payDaySection = [[CTSectionData alloc] init];
    payDaySection.editType = CTCellTypePayDay;
    payDaySection.sectionTitle = @"Pay day";
    [payDaySection.sectionData addObject:payDay];
    CTRowData * entryDate = [CTRowData new];
    entryDate.placeHolder = @"Please select date of entry";
    CTSectionData *entryDateSection = [[CTSectionData alloc] init];
    entryDateSection.editType = CTCellTypeEntryDay;
    entryDateSection.sectionTitle = @"Date of entry";
    [entryDateSection.sectionData addObject:entryDate];
    CTRowData * companyPhone = [CTRowData new];
    companyPhone.tfModel = [[CTTFModel alloc] init];
    companyPhone.placeHolder = @"please input company phone";
    CTSectionData *companyPhoneSection = [[CTSectionData alloc] init];
    companyPhoneSection.editType = CTCellTypeCompanyPhone;
    companyPhoneSection.sectionTitle = @"Company phone";
    [companyPhoneSection.sectionData addObject:companyPhone];
    CTRowData * mail = [CTRowData new];
    mail.tfModel = [[CTTFModel alloc] init];
    mail.placeHolder = @"please input your personal mail";
    CTSectionData *mailSection = [[CTSectionData alloc] init];
    mailSection.editType = CTCellTypeSelectEmail;
    mailSection.sectionTitle = @"Personal mail";
    [mailSection.sectionData addObject:mail];
    [self.dataArray addObject:educationSection];
    [self.dataArray addObject:jobSection];
    [self.dataArray addObject:professionSection];
    [self.dataArray addObject:salarySection];
    [self.dataArray addObject:MaritalSection5];
    [self.dataArray addObject:residenceSection];
    [self.dataArray addObject:homeSection];
    [self.dataArray addObject:citySection];
    [self.dataArray addObject:addressSection];
    [self.dataArray addObject:AlternateSection];
    [self.dataArray addObject:payDaySection];
    [self.dataArray addObject:entryDateSection];
    [self.dataArray addObject:companyPhoneSection];
    [self.dataArray addObject:mailSection];
}
#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CTSectionData *sectionModel = self.dataArray[section];
    return sectionModel.sectionData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTSectionData *sectionModel = self.dataArray[indexPath.section];
    CTRowData *rowModel = sectionModel.sectionData[indexPath.row];
    CTInfoCell *cell = [CTInfoCell cellForTableView:tableView];
    cell.cellType = sectionModel.editType;
    cell.contentTF.text = @""; 
    if (!beNil(rowModel.placeHolder)) {
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:rowModel.placeHolder attributes:
                                          @{NSForegroundColorAttributeName:[UIColor color999]}];
        cell.contentTF.attributedPlaceholder = attrString;
    }
    __weak typeof(self) weakSelf = self;
    switch (sectionModel.editType) {
        case CTCellTypeEducation: {
            cell.contentTF.text = self.model.academicAttainmentLevel.dataCategoryTag;
        }
            break;
        case CTCellTypeJobStatus: {
            cell.contentTF.text = self.model.employmentCondition.dataCategoryTag;
        }
            break;
        case CTCellTypeProfession: {
            cell.contentTF.text = self.model.occupationalRole.dataCategoryTag;
        }
            break;
        case CTCellTypeSalary: {
            cell.contentTF.text = self.model.monthlyEarningsReport.dataCategoryTag;
        }
            break;
        case CTCellTypeMaritalStatus: {
            cell.contentTF.text = self.model.maritalState.dataCategoryTag;
        }
            break;
        case CTCellTypeResidence: {
            cell.contentTF.text = self.model.dwellingCategory.dataCategoryTag;
        }
            break;
        case CTCellTypeHomeStatus: {
            cell.contentTF.text = self.model.residentialStateInfo.dataCategoryTag;
        }
            break;
        case CTCellTypeCity:
        {
            cell.contentTF.text = self.model.residentialDistrictInfo.dataCategoryTag;
        }
            break;
        case CTCellTypeSelectAddress: {
            cell.tfModel = rowModel.tfModel;
            cell.contentTF.text = self.model.residentialAddressDetails;
            cell.contentTF.keyboardType = UIKeyboardTypeDefault;
            cell.editingBlock = ^(CTInfoCell * _Nonnull cell, NSString * _Nonnull content) {
                weakSelf.model.residentialAddressDetails = content;
            };
            cell.editDidEndBlock = ^(CTInfoCell * _Nonnull cell, CTTFModel * _Nonnull tfModel) {
                tfModel.navigationRoute = NSStringFromClass(self.class);
                tfModel.pageIdentity = kct_tf_personinfo_home_details;
                tfModel.elementUniqueIdentifier = kct_tf_personinfo_home_details;
                rowModel.tfModel = tfModel;
                NSDictionary *data = [tfModel model_keyValues];
                [CTUploadManager ct_uploadType:CTUploadTypeTF data:data];
            };
        }
            break;
        case CTCellTypeSelectAlternateNumber: {
            cell.tfModel = rowModel.tfModel;
            cell.contentTF.text = self.model.secondaryContactInfo;
            cell.contentTF.keyboardType = UIKeyboardTypeNumberPad;
            cell.editingBlock = ^(CTInfoCell * _Nonnull cell, NSString * _Nonnull content) {
                if (content.length > 11) {
                    content = [content substringWithRange:NSMakeRange(0, 11)];
                    cell.contentTF.text = [content substringWithRange:NSMakeRange(0, 11)];
                }
                weakSelf.model.secondaryContactInfo = content;
            };
            cell.editDidEndBlock = ^(CTInfoCell * _Nonnull cell, CTTFModel * _Nonnull tfModel) {
                tfModel.navigationRoute = NSStringFromClass(self.class);
                tfModel.pageIdentity = kct_tf_personinfo_otherphone;
                tfModel.elementUniqueIdentifier = kct_tf_personinfo_otherphone;
                rowModel.tfModel = tfModel;
                NSDictionary *data = [tfModel model_keyValues];
                [CTUploadManager ct_uploadType:CTUploadTypeTF data:data];
            };
        }
            break;
        case CTCellTypePayDay: {
            cell.contentTF.text = self.model.salaryDisbursementDate.dataCategoryTag;
        }
            break;
        case CTCellTypeEntryDay: {
            cell.contentTF.text = self.model.employmentCommencement;
        }
            break;
        case CTCellTypeCompanyPhone: {
            cell.tfModel = rowModel.tfModel;
            cell.contentTF.text = self.model.corporateContactNumber;
            cell.contentTF.keyboardType = UIKeyboardTypePhonePad;
            cell.editingBlock = ^(CTInfoCell * _Nonnull cell, NSString * _Nonnull content) {
                if (content.length > 11) {
                    content = [content substringWithRange:NSMakeRange(0, 11)];
                    cell.contentTF.text = [content substringWithRange:NSMakeRange(0, 11)];
                }
                weakSelf.model.corporateContactNumber = content;
            };
            cell.editDidEndBlock = ^(CTInfoCell * _Nonnull cell, CTTFModel * _Nonnull tfModel) {
                tfModel.navigationRoute = NSStringFromClass(self.class);
                tfModel.pageIdentity = kct_tf_company_phone;
                tfModel.elementUniqueIdentifier = kct_tf_company_phone;
                rowModel.tfModel = tfModel;
                NSDictionary *data = [tfModel model_keyValues];
                [CTUploadManager ct_uploadType:CTUploadTypeTF data:data];
            };
        }
            break;
        case CTCellTypeSelectEmail: {
            cell.tfModel = rowModel.tfModel;
            cell.contentTF.text = self.model.electronicMailbox;
            cell.contentTF.keyboardType = UIKeyboardTypeEmailAddress;
            self.currentEmailCell = cell;
            cell.editBeginBlock = ^(CTInfoCell * _Nonnull cell, NSString * _Nonnull content) {
                if ([content containsString:@"@"]) {
                    [weakSelf showEmailList:cell];
                }
            };
            cell.editingBlock = ^(CTInfoCell * _Nonnull cell, NSString * _Nonnull content) {
                weakSelf.model.electronicMailbox = content;
            };
            cell.editDidEndBlock = ^(CTInfoCell * _Nonnull cell, CTTFModel * _Nonnull tfModel) {
                tfModel.navigationRoute = NSStringFromClass(self.class);
                tfModel.pageIdentity = kct_tf_personinfo_email;
                tfModel.elementUniqueIdentifier = kct_tf_personinfo_email;
                rowModel.tfModel = tfModel;
                NSDictionary *data = [tfModel model_keyValues];
                [CTUploadManager ct_uploadType:CTUploadTypeTF data:data];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [YBPopupMenu dismissAllPopupMenu];
                });
            };
        }
            break;
        default:
            break;
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return Ratio(54);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CTSectionData *sectionModel = self.dataArray[section];
    if (sectionModel.editType == CTCellTypeCity) {
        return [UIView new];
    } else {
        CTHeaderTitleView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"CTHeaderTitleView"];
        CTSectionData *sectionModel = self.dataArray[section];
        header.titleLabel.text = sectionModel.sectionTitle;
        return header;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    CTSectionData *sectionModel = self.dataArray[section];
    if (sectionModel.editType == CTCellTypeCity) {
        return CGFLOAT_MIN;
    } else {
        return Ratio(34);
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footer = [[UIView alloc] init];
    footer.backgroundColor = [UIColor color202020];
    return footer;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (CTCreditCellInfo *)toMapCellModel:(CTCreditCellInfo *)cellModel withPickerModel:(CTPickerDataModel *)pickerModel {
    cellModel.attributeCurrentValue = pickerModel.uniqueRecordIdentifier;
    cellModel.hierarchicalParentKey = NSNotFound;
    cellModel.dataCategoryTag = pickerModel.attributeCurrentValue;
    cellModel.statusNarrative = pickerModel.statusNarrative;
    return cellModel;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTSectionData *sectionModel = self.dataArray[indexPath.section];
    __weak typeof(self) weakSelf = self;
    switch (sectionModel.editType) {
        case CTCellTypeEducation: {
            NSArray *arr = [self dealPickerDataSource:self.educationPickerData];
            if (!arr || arr.count == 0) {
                [self loadPickerData];
                return;
            }
            NSDictionary *data = @{
                @"navigationRoute" : NSStringFromClass(self.class),
                @"pageIdentity" : kct_btn_personinfo_education,
                @"elementUniqueIdentifier"  : kct_btn_personinfo_education,
            };
            [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
            [TJPickerView showStringPickerWithTitle:sectionModel.sectionTitle dataSources:arr selectValue:arr.firstObject completion:^(NSString * _Nonnull select) {
                NSInteger index = [arr indexOfObject:select];
                CTPickerDataModel *pickerModel = [self.educationPickerData objectAtIndex:index];
                weakSelf.model.academicAttainmentLevel = [weakSelf toMapCellModel:weakSelf.model.academicAttainmentLevel withPickerModel:pickerModel];
                [weakSelf.tableView reloadData];
            }];
        }
            break;
        case CTCellTypeJobStatus: {
            NSArray *arr = [self dealPickerDataSource:self.jobPickerData];
            if (!arr || arr.count == 0) {
                [self loadPickerData];
                return;
            }
            NSDictionary *data = @{
                @"navigationRoute" : NSStringFromClass(self.class),
                @"pageIdentity" : kct_btn_job_status,
                @"elementUniqueIdentifier"  : kct_btn_job_status,
            };
            [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
            [TJPickerView showStringPickerWithTitle:sectionModel.sectionTitle dataSources:arr selectValue:arr.firstObject completion:^(NSString * _Nonnull select) {
                NSInteger index = [arr indexOfObject:select];
                CTPickerDataModel *pickerModel = [self.jobPickerData objectAtIndex:index];
                weakSelf.model.employmentCondition = [weakSelf toMapCellModel:weakSelf.model.employmentCondition withPickerModel:pickerModel];
                [weakSelf.tableView reloadData];
            }];
        }
            break;
        case CTCellTypeProfession: {
            NSArray *arr = [self dealPickerDataSource:self.professionPickerData];
            if (!arr || arr.count == 0) {
                [self loadPickerData];
                return;
            }
            NSDictionary *data = @{
                @"navigationRoute" : NSStringFromClass(self.class),
                @"pageIdentity" : kct_btn_person_occupation,
                @"elementUniqueIdentifier"  : kct_btn_person_occupation,
            };
            [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
            [TJPickerView showStringPickerWithTitle:sectionModel.sectionTitle dataSources:arr selectValue:arr.firstObject completion:^(NSString * _Nonnull select) {
                NSInteger index = [arr indexOfObject:select];
                CTPickerDataModel *pickerModel = [self.professionPickerData objectAtIndex:index];
                weakSelf.model.occupationalRole = [weakSelf toMapCellModel:weakSelf.model.occupationalRole withPickerModel:pickerModel];
                [weakSelf.tableView reloadData];
            }];
        }
            break;
        case CTCellTypeSalary: {
            NSArray *arr = [self dealPickerDataSource:self.salaryPickerData];
            if (!arr || arr.count == 0) {
                [self loadPickerData];
                return;
            }
            NSDictionary *data = @{
                @"navigationRoute" : NSStringFromClass(self.class),
                @"pageIdentity" : kct_btn_personinfo_monthIncome,
                @"elementUniqueIdentifier"  : kct_btn_personinfo_monthIncome,
            };
            [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
            [TJPickerView showStringPickerWithTitle:sectionModel.sectionTitle dataSources:arr selectValue:arr.firstObject completion:^(NSString * _Nonnull select) {
                NSInteger index = [arr indexOfObject:select];
                CTPickerDataModel *pickerModel = [self.salaryPickerData objectAtIndex:index];
                weakSelf.model.monthlyEarningsReport = [weakSelf toMapCellModel:weakSelf.model.monthlyEarningsReport withPickerModel:pickerModel];
                [weakSelf.tableView reloadData];
            }];
        }
            break;
        case CTCellTypeMaritalStatus: {
            NSArray *arr = [self dealPickerDataSource:self.maritalPickerData];
            if (!arr || arr.count == 0) {
                [self loadPickerData];
                return;
            }
            NSDictionary *data = @{
                @"navigationRoute" : NSStringFromClass(self.class),
                @"pageIdentity" : kct_btn_personinfo_marriage,
                @"elementUniqueIdentifier"  : kct_btn_personinfo_marriage,
            };
            [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
            [TJPickerView showStringPickerWithTitle:sectionModel.sectionTitle dataSources:arr selectValue:arr.firstObject completion:^(NSString * _Nonnull select) {
                NSInteger index = [arr indexOfObject:select];
                CTPickerDataModel *pickerModel = [self.maritalPickerData objectAtIndex:index];
                weakSelf.model.maritalState = [weakSelf toMapCellModel:weakSelf.model.maritalState withPickerModel:pickerModel];
                [weakSelf.tableView reloadData];
            }];
        }
            break;
        case CTCellTypeResidence: {
            NSArray *arr = [self dealPickerDataSource:self.residencePickerData];
            if (!arr || arr.count == 0) {
                [self loadPickerData];
                return;
            }
            NSDictionary *data = @{
                @"navigationRoute" : NSStringFromClass(self.class),
                @"pageIdentity" : kct_btn_personinfo_houseowner,
                @"elementUniqueIdentifier"  : kct_btn_personinfo_houseowner,
            };
            [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
            [TJPickerView showStringPickerWithTitle:sectionModel.sectionTitle dataSources:arr selectValue:arr.firstObject completion:^(NSString * _Nonnull select) {
                NSInteger index = [arr indexOfObject:select];
                CTPickerDataModel *pickerModel = [self.residencePickerData objectAtIndex:index];
                weakSelf.model.dwellingCategory = [weakSelf toMapCellModel:weakSelf.model.dwellingCategory withPickerModel:pickerModel];
                [weakSelf.tableView reloadData];
            }];
        }
            break;
        case CTCellTypeHomeStatus: {
            NSArray *arr = [self dealPickerDataSource:self.homeStatePickerData];
            if (!arr || arr.count == 0) {
                [self loadPickerData];
                return;
            }
            NSDictionary *data = @{
                @"navigationRoute" : NSStringFromClass(self.class),
                @"pageIdentity" : kct_btn_personinfo_home_province,
                @"elementUniqueIdentifier"  : kct_btn_personinfo_home_province,
            };
            [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
            [TJPickerView showStringPickerWithTitle:sectionModel.sectionTitle dataSources:arr selectValue:arr.firstObject completion:^(NSString * _Nonnull select) {
                NSInteger index = [arr indexOfObject:select];
                CTPickerDataModel *pickerModel = [self.homeStatePickerData objectAtIndex:index];
                weakSelf.model.residentialStateInfo = [weakSelf toMapCellModel:weakSelf.model.residentialStateInfo withPickerModel:pickerModel];
                [weakSelf.tableView reloadData];
            }];
        }
            break;
        case CTCellTypeCity: {
            if (self.model.residentialStateInfo != nil) {
                [self loadCityPickerDatas:indexPath.section];
                NSDictionary *data = @{
                    @"navigationRoute" : NSStringFromClass(self.class),
                    @"pageIdentity" : kct_btn_personinfo_home_city,
                    @"elementUniqueIdentifier"  : kct_btn_personinfo_home_city,
                };
                [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
            } else {
                [self.view showText:@"Please select State of home first"];
            }
            return;
        }
            break;
        case CTCellTypePayDay: {
            NSArray *arr = [self dealPickerDataSource:self.payDayPickerData];
            if (!arr || arr.count == 0) {
                [self loadPickerData];
                return;
            }
            NSDictionary *data = @{
                @"navigationRoute" : NSStringFromClass(self.class),
                @"pageIdentity" : kct_btn_salary_date_time,
                @"elementUniqueIdentifier"  : kct_btn_salary_date_time,
            };
            [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
            [TJPickerView showStringPickerWithTitle:sectionModel.sectionTitle dataSources:arr selectValue:arr.firstObject completion:^(NSString * _Nonnull select) {
                NSInteger index = [arr indexOfObject:select];
                CTPickerDataModel *pickerModel = [self.payDayPickerData objectAtIndex:index];
                weakSelf.model.salaryDisbursementDate = [weakSelf toMapCellModel:weakSelf.model.salaryDisbursementDate withPickerModel:pickerModel];
                [weakSelf.tableView reloadData];
            }];
        }
            break;
        case CTCellTypeEntryDay: {
            NSDictionary *data = @{
                @"navigationRoute" : NSStringFromClass(self.class),
                @"pageIdentity" : kct_btn_company_entry_time,
                @"elementUniqueIdentifier"  : kct_btn_company_entry_time,
            };
            [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
            TJPickerView *picker = [[TJPickerView alloc] initWithTitle:@"Date of entry" pickerMode:BRDatePickerModeYMD minDate:nil maxDate:nil completion:^(NSDate *selectDate, NSString *selectValue) {
                NSString *dateStr = [NSDate br_getDateString:selectDate format:@"dd/MM/yyyy"];
                self.model.employmentCommencement = dateStr;
                [weakSelf.tableView reloadData];
            }];
            [picker show];
            return;
        }
            break;
        default:
            break;
    }
}
- (NSArray *)dealPickerDataSource:(NSArray *)dataArray {
    if (dataArray.count == 0) {
        return nil;
    }
    NSMutableArray *arrM = [NSMutableArray array];
    [dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CTPickerDataModel *model = obj;
        [arrM addObject:model.attributeCurrentValue];
    }];
    return arrM;
}
#pragma mark - YBPopupMenu
- (void)showEmailList:(CTInfoCell *)cell {
    if (self.hasPopupMenu) {
        return;
    }
    self.hasPopupMenu = YES;
    [YBPopupMenu showAtPoint:CGPointMake(kScreenWidth*0.5, kScreenHeight*0.5) titles:self.emailTypes icons:@[] menuWidth:cell.ct_width-Ratio(32) otherSettings:^(YBPopupMenu *popupMenu) {
        popupMenu.delegate = self;
        popupMenu.backColor = [UIColor whiteColor];
        popupMenu.textColor = [UIColor blackColor];
        popupMenu.dismissOnSelected = NO;
        popupMenu.showShadow = NO;
        popupMenu.showMaskView = NO;
        popupMenu.itemHeight = Ratio(40);
        popupMenu.cornerRadius = Ratio(12);
        popupMenu.rectCorner = UIRectCornerAllCorners;
        popupMenu.borderWidth = 1;
        popupMenu.animationManager.style = YBPopupMenuAnimationStyleNone;
        popupMenu.arrowDirection = YBPopupMenuArrowDirectionBottom;
        popupMenu.priorityDirection = YBPopupMenuPriorityDirectionBottom;
        popupMenu.arrowWidth = 0;
        popupMenu.arrowHeight = 0;
    }];
}
- (void)ybPopupMenu:(YBPopupMenu *)ybPopupMenu didSelectedAtIndex:(NSInteger)index {
    NSString *emailAddr = [self.emailTypes objectAtIndex:index];
    self.currentEmailCell.contentTF.text = [NSString stringWithFormat:@"%@%@", self.currentEmailCell.contentTF.text, emailAddr];
    self.model.electronicMailbox = self.currentEmailCell.contentTF.text;
    [ybPopupMenu dismiss];
}
- (void)ybPopupMenuDidDismiss:(YBPopupMenu *)ybPopupMenu {
    self.hasPopupMenu = NO;
}
#pragma mark - setting && getting
- (UITableView *)tableView
{
    if (_tableView==nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth-Ratio(20), [UIDevice ct_viewHeight]-Ratio(66) - Ratio(90) - [UIDevice ct_safeBottom]) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.scrollEnabled = YES;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[CTHeaderTitleView class] forHeaderFooterViewReuseIdentifier:@"CTHeaderTitleView"];
        UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _tableView.ct_width, Ratio(80))];
        footer.backgroundColor = [UIColor whiteColor];
        _tableView.tableFooterView = footer;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
        }
    }
    return _tableView;
}
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (UIButton *)nextButton
{
    if (!_nextButton) {
        _nextButton = [[UIButton alloc] init];
        _nextButton.frame = CGRectMake((Ratio(10)), self.tableView.ct_bottom + Ratio(20),kScreenWidth - Ratio(40), Ratio(50));
        [_nextButton setBackgroundColor:[UIColor colorFF6C2E]];
        [_nextButton setTitleColor: [UIColor colorFFF] forState:UIControlStateNormal];
        _nextButton.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:Ratio(20)];
        [_nextButton setTitle:@"Next" forState:UIControlStateNormal];
        _nextButton.layer.cornerRadius = Ratio(10);
        _nextButton.layer.masksToBounds = YES;
        [_nextButton addTarget:self action:@selector(nextButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextButton;
}
#pragma mark - Action
- (void)nextFailPoint {
    NSDictionary *credtiData = @{
        @"tokenUniqueIdentifier"  : returnBeNil(self.pageModel.operationalTaskID),
        @"errorFlag" : kpage_personinfo_nextFailPoint,
    };
    [CTUploadManager ct_uploadType:CTUploadTypeCredit data:credtiData];
}
- (void)nextButtonClick {
    if (!self.model.academicAttainmentLevel || !self.model.employmentCondition || !self.model.occupationalRole || !self.model.monthlyEarningsReport || !self.model.maritalState || !self.model.dwellingCategory || !self.model.residentialStateInfo || !self.model.residentialDistrictInfo || beNil(self.model.residentialAddressDetails) || !self.model.salaryDisbursementDate || !self.model.employmentCommencement || beNil(self.model.corporateContactNumber) || beNil(self.model.electronicMailbox)) {
        [self.view showText:@"Please complete the information"];
        [self nextFailPoint];
        return;
    }
    if (![self.model.corporateContactNumber isMobileFormated]) {
        [self.view showText:@"The phone format is incorrect"];
        [self nextFailPoint];
        return;
    }
    if (!beNil(self.model.secondaryContactInfo) && ![self.model.secondaryContactInfo isMobileFormated]) {
        [self.view showText:@"The phone format is incorrect"];
        [self nextFailPoint];
        return;
    }
    if (![self.model.residentialAddressDetails isAddressFormated]) {
        [self.view showText:@"The address format is incorrect"];
        [self nextFailPoint];
        return;
    }
    if (![self.model.electronicMailbox isEmailFormated]) {
        [self.view showText:@"The mailbox format is incorrect"];
        [self nextFailPoint];
        return;
    }
    NSDictionary *data = @{
        @"navigationRoute" : NSStringFromClass(self.class),
        @"pageIdentity" : kct_btn_personinfo_next,
        @"elementUniqueIdentifier"  : kct_btn_personinfo_next,
    };
    [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
    NSDictionary *cacheDic = @{
        @"userGroup" : returnBeNil([CTUserManager shareManager].userModel.userGroup),
        @"crucialIdentifier" : @"communicationDetails",
        @"attributeCurrentValue" : [self.model mj_JSONString],
    };
    [self.view showLoading];
    [CTBaseRequest postRequestWithMethodName:CTPath(@"/setCreditResult", CTPathTypePost, nil) parametersDic:cacheDic success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        [self.view dismissLoading];
        NSDictionary *credtiData = @{
            @"tokenUniqueIdentifier"  : returnBeNil(self.pageModel.operationalTaskID),
            @"errorFlag" : kpage_personinfo_nextSucPoint,
        };
        [CTUploadManager ct_uploadType:CTUploadTypeCredit data:credtiData];
        if (self.nextClickBlock) {
            self.nextClickBlock();
        }
    }];
}
- (CTPersonalModel *)model {
    if (!_model) {
        _model = [[CTPersonalModel alloc] init];
    }
    return _model;
}
@end
